<template>
    <div class="associate-wrap">
        <div class="associate-table-wrap">
            <el-table
                :data="list"
                height="400"
                ref="multipleTable"
                row-key="id">
                <el-table-column
                        prop="content"
                        align="center"
                        label="内容">
                    <template slot-scope="scope">
                        {{ scope.row.content && scope.row.content.content_name }}
                        <span v-if="scope.row.alias || scope.row.content.content_code">
                            ({{scope.row.alias || scope.row.content.content_code}})
                        </span>
                        <el-button type="text" size="mini"
                                   v-if="scope.row.isEditing"
                                   @click="handleSelectContent(scope.row)" >选择</el-button>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="alias"
                    align="center"
                    label="别名">
                    <template slot-scope="scope">
                        <template v-if="scope.row.isEditing">
                            <el-input v-model="scope.row.alias" size="mini" placeholder="别名"></el-input>
                        </template>
                        <template v-else>
                            {{ scope.row.alias }}
                        </template>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="filter"
                    align="center"
                    label="过滤">
                    <template slot-scope="scope">
                        <template v-if="scope.row.isEditing">
                            <el-input v-model="scope.row.filter" size="mini" placeholder="过滤"></el-input>
                        </template>
                        <template v-else>
                            {{ scope.row.alias }}
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <template v-if="scope.row.isTemping || scope.row.isEditing">
                            <el-button type="primary" @click="handleRowSave(scope.row, scope.$index)" size="mini">保 存</el-button>
                            <el-button @click="handleRowCancel(scope.row, scope.$index)" size="mini">取 消</el-button>
                        </template>
                        <template v-else>
                            <el-button @click="handleRowEdit(scope.row, scope.$index)" size="mini">修 改</el-button>
                        </template>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!--<el-button type="primary" @click="handleAddRow()">添加内容</el-button>-->
        <div class="btns" style="text-align: center;padding-top: 20px;">
            <el-button type="primary" @click="handleAddRow()">添加内容</el-button>
            <el-button @click="close()">关 闭</el-button>
        </div>


        <el-dialog title="选择内容" :visible.sync="showContent" top="60px" width="650px" :append-to-body="true">
            <c-content @close="closeContentWin" :show.sync="showContent" :is-single="true"></c-content>
        </el-dialog>
    </div>
</template>

<script>
    import { mapState, mapActions } from 'vuex';
    import axios from 'axios';
    import _ from 'lodash';
    import cContent from './contents';

    export default {
        props: [ 'rid', 'show' ],
        data() {
            return {
                list: [],
                loading: false,

                currentEdit: null,
                currentCopy: null,
                showContent: false,
            }
        },
        components: {
            cContent
        },
        created: function () {
            // this.pid = this.$route.query.pid;
        },
        mounted: function () {
            // this.groupId = this.$route.params.groupId;
            // this.init();
            this.init();
        },
        watch: {
            'show'(val) {
                if(val) {
                    this.init();
                }
            }
        },
        computed: {
            ...mapState([

            ]),
        },
        methods: {
            ...mapActions([
            ]),
            init() {
                this.refresh();
            },
            refresh() {
                axios.get('/mgr/api/page/web/contents', {
                    params : {
                        page_id: this.rid
                    }
                }).then(({ data }) => {
                    if(_.get(data, 'code') == 200) {
                        this.list = _.get(data, 'data', []);
                    }
                })
            },
            submit(item) {
                this.loading = true;

                axios.post('/mgr/api/page/web/content/upsert', item)
                .then(({ data }) => {
                    this.loading = false;

                    if(_.get(data, 'code') == 200) {
                        this.$message('操作成功！');
                        let nd = _.get(data, 'data', {});

                        _.assign(item, nd);

                        item.isTemping = false;
                        item.isEditing = false;
                    } else {
                        this.$message('操作失败！');
                    }
                })
                .catch((error) => {
                    this.loading = false;
                    this.$alert('操作失败，请稍后再试！');
                })
            },
            handleSelectionChange(selection) {
                // console.log(selection);
            },
            _delete(it, type) {
                axios.post(`/mgr/api/page/web/content/remove`, {
                    page_id: it.page_content_rel_id
                }).then(({ data }) => {
                    this.refresh();
                }).catch((error) => {
                    this.$alert('操作失败，请稍后再试！');
                })
            },
            handleRemove(it) {

                if(!it || !it.page_content_rel_id) {
                    return;
                }
                this.$confirm(`确定删除内容【${it.content.content_name}】, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this._delete(it, 'remove');
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            handleAddRow() {

                var exist = _.find(this.list, { isTemping: true });

                if(exist) {
                    this.$alert('请将列表中临时新增的先保存或取消。');
                    return;
                }

                let row = {
                    page_id: this.rid,
                    content_id: '',
                    content: {},
                    alias: '',
                    filter: '',
                    isTemping: true,
                    isEditing: true
                };

                this.currentEdit = row;
                this.list.push(row);
            },
            close(flag) {
                this.$emit('close', flag);
            },
            handleRowEdit(row, idx) {

                row.isEditing = true;
                this.currentCopy = _.clone(row);
                this.currentEdit = row;
                this.$set(this.list, idx, row);
            },
            handleRowSave(row, idx) {
                this.loading = true;

                axios.post(`/mgr/api/page/web/content/upsert`, row)
                    .then(({ data }) => {
                        this.loading = false;

                        if(_.get(data, 'code') == 200) {
                            this.$message('操作成功！');
                            let nd = _.get(data, 'data', {});

                            _.assign(row, nd);

                            row.isTemping = false;
                            row.isEditing = false;

                            this.$set(this.list, idx, row);
                        } else {
                            this.$message('操作失败！');
                        }
                    })
                    .catch((error) => {
                        this.loading = false;
                        this.$alert('操作失败，请稍后再试！');
                    })
            },
            handleRowCancel(row, idx) {

                row.isEditing = false;

                if(row.isTemping) {
                    this.list.splice(idx, 1);
                } else {
                    this.currentCopy.isEditing = false;
                    this.$set(this.list, idx, this.currentCopy);
                }
            },
            handleSelectContent() {
                this.showContent = true;
            },
            closeContentWin(cnt){

                this.showContent = false;

                if(_.isArray(cnt) && cnt[0] && cnt[0].content_id) {
                    this.currentEdit.content = cnt[0];
                    this.currentEdit.content_id = cnt[0].content_id;
                }
            },
        }
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
    .associate-table-wrap {
        border: 1px solid #EEE;

        thead .el-checkbox {
            margin-bottom:0px;
        }
    }
</style>
